/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package gestionmagasins_aspectj_junit_patterns.forms;

import gestionmagasins_aspectj_junit_patterns.GestionMagasinsMain;
import gestionmagasins_aspectj_junit_patterns.model.Article;
import gestionmagasins_aspectj_junit_patterns.model.CatalogueArticles;
import gestionmagasins_aspectj_junit_patterns.model.CatalogueClients;
import gestionmagasins_aspectj_junit_patterns.model.CatalogueUsagers;
import gestionmagasins_aspectj_junit_patterns.model.CatalogueVente;
import gestionmagasins_aspectj_junit_patterns.model.Client;
import gestionmagasins_aspectj_junit_patterns.model.RoleVendeur;
import gestionmagasins_aspectj_junit_patterns.model.Taxe;
import gestionmagasins_aspectj_junit_patterns.model.Vente;
import gestionmagasins_aspectj_junit_patterns.model.Usager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 *
 * @author James
 */
public class ManageSalesJFrame extends CustomJFrame {

    CatalogueVente catalogue;
    private final DefaultListModel<Vente> salesListModel;
    private final DefaultListModel<Article> productsListModel;
    //private final DefaultListModel<Paiement> paymentListModel;
    private final DefaultComboBoxModel articleComboBoxModel;
    private final DefaultComboBoxModel clientsComboBoxModel;
    private final DefaultComboBoxModel salesmenComboBoxModel;
    private final ManageSalesJFrame.ClientChangeListener clientSelectionChange;
    private final ManageSalesJFrame.SalesmanChangeListener salesmanSelectionChange;
    private Vente currentSale;
    private boolean isNewSale;
    private boolean mustSave;
    
    /**
     * Creates new form ManageSalesJFrame
     */
    ManageSalesJFrame(MainMenuJFrame mainMenu, Usager usager) 
    {
        super(mainMenu, usager);
        
        initComponents();
        this.initKeyListeners();
        
        clientSelectionChange = new ManageSalesJFrame.ClientChangeListener();
        salesmanSelectionChange = new ManageSalesJFrame.SalesmanChangeListener();
        currentSale = null;
        mustSave = false;
        isNewSale = false;
        
        //Initialition des GroupBox
        saleDetailsJPanel.setBorder(BorderFactory.createTitledBorder("Détails de la vente"));
        
        //Initialisation du TextChangedListener de la recherche
        salesSearchJText.getDocument().addDocumentListener(searchDocumentListener);
        
        //Initialisation de la liste de ventes
        salesListModel = new DefaultListModel<>();
        salesJList.setModel(salesListModel);

        productsListModel = new DefaultListModel<>();
        productsJList.setModel(productsListModel);
        
        //paymentListModel = new DefaultListModel<>();
        //paymentJList.setModel(paymentListModel);
        
        //Affichage de toutes les ventes
        catalogue = CatalogueVente.getCatalogueVente();
        
        for(Vente v : catalogue.getVentes())
            salesListModel.addElement(v);
        
        salesJList.addListSelectionListener(listSelectItemListener);
        
        
        
        //Initialisation de la liste des vendeurs
        salesmenComboBoxModel = new DefaultComboBoxModel<>();
        salesmanJComboBox.setModel(salesmenComboBoxModel);
        
        for(Usager u : CatalogueUsagers.getInstance().getActivated())
            if(u.getRole() instanceof RoleVendeur)
                salesmenComboBoxModel.addElement(u);
        
        //Initialisation de la liste de roles
        clientsComboBoxModel = new DefaultComboBoxModel<>();
        clientJComboBox.setModel(clientsComboBoxModel);
        
        for(Client c : CatalogueClients.getInstance().getClientsActif())
            clientsComboBoxModel.addElement(c);
        
        articleComboBoxModel = new DefaultComboBoxModel<>();
        articleJComboBox.setModel(articleComboBoxModel);
        
        for(Article a : CatalogueArticles.getCatalogueArticles().getListe())
            articleComboBoxModel.addElement(a);
        
        /*DefaultComboBoxModel paymentTypeComboBoxModel = new DefaultComboBoxModel<>();
        paymentJComboBox.setModel(paymentTypeComboBoxModel);
        
        paymentTypeComboBoxModel.addElement("Cheque");
        paymentTypeComboBoxModel.addElement("Comptant");
        paymentTypeComboBoxModel.addElement("Cheque");
        
        btnRemovePayment.setEnabled(false);*/
        btnRemoveProduct.setEnabled(false);
        saleSelected(null, false);
    }

    @Override
    protected void formClosing()
    {
        if(verifySaveStatus())
        {
            super.formClosing();
        }
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        salesSearchJText = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        salesJList = new javax.swing.JList();
        saleDetailsJPanel = new javax.swing.JPanel();
        clientJComboBox = new javax.swing.JComboBox();
        jLabel15 = new javax.swing.JLabel();
        jLabel16 = new javax.swing.JLabel();
        salesmanJComboBox = new javax.swing.JComboBox();
        jLabel17 = new javax.swing.JLabel();
        dtpSalesDate = new org.jdesktop.swingx.JXDatePicker();
        btnRemoveProduct = new javax.swing.JButton();
        btnAddProduct = new javax.swing.JButton();
        btnAddPayment = new javax.swing.JButton();
        btnRemovePayment = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        lblSubTotal = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        lblTaxes = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        lblTotal = new javax.swing.JLabel();
        btnPrintInvoice = new javax.swing.JButton();
        articleJComboBox = new javax.swing.JComboBox();
        jScrollPane2 = new javax.swing.JScrollPane();
        productsJList = new javax.swing.JList();
        jScrollPane3 = new javax.swing.JScrollPane();
        paymentJList = new javax.swing.JList();
        newSaleJButton = new javax.swing.JButton();
        deleteSaleJButton = new javax.swing.JButton();
        saveSaleJButton = new javax.swing.JButton();
        cancelJButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Super Logiciel inc.");

        jLabel1.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N
        jLabel1.setText("Gestion des ventes");

        salesSearchJText.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                salesSearchJTextActionPerformed(evt);
            }
        });

        jLabel2.setText("Rechercher ");

        salesJList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        salesJList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(salesJList);

        saleDetailsJPanel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        saleDetailsJPanel.setToolTipText("Details de la vente");

        clientJComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel15.setText("Client");
        jLabel15.setToolTipText("");

        jLabel16.setText("Vendeur");

        salesmanJComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel17.setText("Date");

        dtpSalesDate.setName("dtpDateNaissanceClient"); // NOI18N

        btnRemoveProduct.setText("-");
        btnRemoveProduct.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoveProductActionPerformed(evt);
            }
        });

        btnAddProduct.setText("+");
        btnAddProduct.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddProductActionPerformed(evt);
            }
        });

        btnAddPayment.setText("+");
        btnAddPayment.setEnabled(false);

        btnRemovePayment.setText("-");
        btnRemovePayment.setEnabled(false);
        btnRemovePayment.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemovePaymentActionPerformed(evt);
            }
        });

        jLabel3.setText("Sous-total:");

        lblSubTotal.setText("jLabel3");

        jLabel5.setText("Taxes:");

        lblTaxes.setText("jLabel3");

        jLabel7.setText("Total:");

        lblTotal.setText("jLabel3");

        btnPrintInvoice.setText("Imprimer la facture");

        articleJComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        productsJList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane2.setViewportView(productsJList);

        paymentJList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        paymentJList.setEnabled(false);
        jScrollPane3.setViewportView(paymentJList);

        javax.swing.GroupLayout saleDetailsJPanelLayout = new javax.swing.GroupLayout(saleDetailsJPanel);
        saleDetailsJPanel.setLayout(saleDetailsJPanelLayout);
        saleDetailsJPanelLayout.setHorizontalGroup(
            saleDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(saleDetailsJPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(saleDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(saleDetailsJPanelLayout.createSequentialGroup()
                        .addGroup(saleDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(articleJComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, saleDetailsJPanelLayout.createSequentialGroup()
                                .addGroup(saleDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel17)
                                    .addComponent(jLabel16)
                                    .addComponent(jLabel15))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(saleDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(clientJComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(salesmanJComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(dtpSalesDate, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                            .addComponent(jScrollPane2)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, saleDetailsJPanelLayout.createSequentialGroup()
                                .addGap(41, 41, 41)
                                .addComponent(btnPrintInvoice)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 68, Short.MAX_VALUE)
                                .addGroup(saleDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel7)
                                    .addComponent(jLabel5))
                                .addGap(57, 57, 57)
                                .addGroup(saleDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lblSubTotal)
                                    .addComponent(lblTaxes)
                                    .addComponent(lblTotal))))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(saleDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btnRemoveProduct, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnAddProduct, javax.swing.GroupLayout.Alignment.TRAILING)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, saleDetailsJPanelLayout.createSequentialGroup()
                        .addComponent(jScrollPane3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(saleDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btnAddPayment, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(btnRemovePayment, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
        saleDetailsJPanelLayout.setVerticalGroup(
            saleDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(saleDetailsJPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(saleDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel16)
                    .addComponent(salesmanJComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(saleDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel15)
                    .addComponent(clientJComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(saleDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel17)
                    .addComponent(dtpSalesDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(saleDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(saleDetailsJPanelLayout.createSequentialGroup()
                        .addComponent(btnAddProduct, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnRemoveProduct, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(saleDetailsJPanelLayout.createSequentialGroup()
                        .addComponent(articleJComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(saleDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(saleDetailsJPanelLayout.createSequentialGroup()
                        .addComponent(btnAddPayment, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnRemovePayment, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE)
                .addGroup(saleDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(saleDetailsJPanelLayout.createSequentialGroup()
                        .addGroup(saleDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(lblSubTotal))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(saleDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(lblTaxes))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(saleDetailsJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel7)
                            .addComponent(lblTotal)))
                    .addComponent(btnPrintInvoice)))
        );

        newSaleJButton.setText("Nouveau");
        newSaleJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newSaleJButtonActionPerformed(evt);
            }
        });

        deleteSaleJButton.setText("Supprimer");
        deleteSaleJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteSaleJButtonActionPerformed(evt);
            }
        });

        saveSaleJButton.setText("Enregistrer");
        saveSaleJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveSaleJButtonActionPerformed(evt);
            }
        });

        cancelJButton.setText("Annuler");
        cancelJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelJButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(13, 13, 13)
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(salesSearchJText, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 292, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(82, 82, 82)
                                .addComponent(newSaleJButton)
                                .addGap(18, 18, 18)
                                .addComponent(deleteSaleJButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(saveSaleJButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cancelJButton))
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(saleDetailsJPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap(159, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(salesSearchJText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane1))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(saleDetailsJPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(newSaleJButton)
                            .addComponent(saveSaleJButton)
                            .addComponent(cancelJButton)
                            .addComponent(deleteSaleJButton))))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void salesSearchJTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_salesSearchJTextActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_salesSearchJTextActionPerformed

    private void newSaleJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newSaleJButtonActionPerformed

        salesJList.clearSelection();
        salesmanJComboBox.requestFocus();

        isNewSale = true;
        saleSelected(new Vente(), isNewSale);
    }//GEN-LAST:event_newSaleJButtonActionPerformed

    private void deleteSaleJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteSaleJButtonActionPerformed

        delete();
    }//GEN-LAST:event_deleteSaleJButtonActionPerformed

    private void saveSaleJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveSaleJButtonActionPerformed

        save();
    }//GEN-LAST:event_saveSaleJButtonActionPerformed

    private boolean save()
    {
        if(fieldsAreValid())
        {
            
            catalogue.toString();
            copyFieldsToSale();
            
            if(isNewSale)
            {
                
                catalogue.addVente(currentSale);
                salesListModel.addElement(currentSale);
                
                isNewSale = false;
            }
            
            salesJList.updateUI();
            setMustSave(false);
            
            return true;
        }
        else
            return false;
    }
    
    private void delete()
    {
        if(askForConfirmation("Êtes-vous sûr de vouloir supprimer cet usager?"))
        {
            if(!isNewSale)
            {
                if(CatalogueVente.getCatalogueVente().removeVente(currentSale))
                {
                    salesListModel.removeElement(currentSale);
                    salesJList.updateUI();
                }
            }
        
            setMustSave(false);
            saleSelected(null, false);
        }
    }
    
    private void updateTotals()
    {
        double sousTotal = 0;
        double taxes = 0;
        
        for(Object a : productsListModel.toArray())
        {
            sousTotal += ((Article)a).getPrix();
            for(Taxe t : ((Article)a).getTaxes())
                taxes += ((Article)a).getPrix() * t.getTauxCourant();
        }
        
        lblTotal.setText(""+(sousTotal+taxes));
        lblSubTotal.setText(""+sousTotal);
        lblTaxes.setText(""+taxes);
    }
    
    private void addProduct() 
    {
        catalogue.toString();
        Article productToAdd = (Article) articleJComboBox.getSelectedItem();
        productsListModel.addElement(productToAdd);
        setMustSave(true);
        btnRemoveProduct.setEnabled(true);
        updateTotals();
    }
    
    private void removeProduct() 
    {
        Article productToRemove = (Article)productsJList.getSelectedValue();

        if(productsListModel.contains(productToRemove)){
            productsListModel.removeElement(productToRemove);
            setMustSave(true);
            
            if(productsListModel.isEmpty())
                btnRemoveProduct.setEnabled(false);
            updateTotals();
        }
    }
    
    /*private void removePayment() 
    {
        Paiement paymentToRemove = (Paiement)paymentJList.getSelectedValue();

        if(paymentListModel.contains(paymentToRemove)){
            paymentListModel.removeElement(paymentToRemove);
            setMustSave(true);
            
            if(paymentListModel.isEmpty())
                btnRemovePayment.setEnabled(false);
        }
    }*/
    
    private void setMustSave(boolean status) 
    {
        mustSave = status;
        saveSaleJButton.setEnabled(mustSave);
        salesJList.setEnabled(!status);
        salesSearchJText.setEnabled(!status);
    }
    
    private boolean askForConfirmation(String message) 
    {
        int dialogResult = JOptionPane.showConfirmDialog(this, message, "Attention", JOptionPane.YES_NO_OPTION);
        
        return dialogResult == 0;//Si == 0 -> oui
    }
    
    private void setFieldsEnabled(boolean enabled) 
    {
        dtpSalesDate.setEditable(enabled);
        
        clientJComboBox.setEnabled(enabled);
        salesmanJComboBox.setEnabled(enabled);
        articleJComboBox.setEnabled(enabled);
        
        productsJList.setEnabled(enabled);
        //paymentJList.setEnabled(enabled);
        
        btnAddProduct.setEnabled(enabled);
        //btnAddPayment.setEnabled(enabled);
    }

    private void setButtonsEnabled(boolean buttonNew, boolean buttonDelete, boolean buttonSave, boolean buttonCancel) 
    {
        newSaleJButton.setEnabled(buttonNew);
        deleteSaleJButton.setEnabled(buttonDelete);
        saveSaleJButton.setEnabled(buttonSave);
        cancelJButton.setEnabled(buttonCancel);
    }
    
    private void clearFields()
    {
        lblSubTotal.setText("0");
        lblTaxes.setText("0");
        lblTotal.setText("0");
        dtpSalesDate.setDate(null);
        
        if(clientsComboBoxModel.getSize() > 0)
            clientJComboBox.setSelectedIndex(0);
        if(salesmenComboBoxModel.getSize() > 0)
            salesmanJComboBox.setSelectedIndex(0);
        
        productsListModel.clear();
        //paymentListModel.clear();
    }
    
    private boolean verifySaveStatus()//Retourne TRUE si la sauvegarde a fonctionnnée ou n'avait pas besoin de sauvegarder et FALSE si la sauvegarde a échoué
    {
        if(mustSave && askForConfirmation("Voulez-vous sauvegarder les changements effectués?"))
        {
            return save();
        }
        else
        {
            setMustSave(false);
            
            return true;
        }
    }
    
    private void copyFieldsToSale() 
    {
        currentSale.setClient((Client) clientJComboBox.getSelectedItem());
        currentSale.setVendeur((Usager) salesmanJComboBox.getSelectedItem());
        
        currentSale.setDate(dtpSalesDate.getDate());
        currentSale.setEtat(Vente.EtatsVente.Ouverte);
        catalogue.toString();
        currentSale.getListeArticles().clear();
        
        for(Object a : productsListModel.toArray())
        {
            currentSale.ajouterArticle((Article)a);
        }
        
        /*for(Object p : paymentListModel.toArray())
        {
            currentSale.ajouterPaiement((Paiement)p);
        }*/
    }
    
    private boolean fieldsAreValid() 
    {
        String errorMessage = "";
       
        if(dtpSalesDate.getDate().after(new Date()))
        {
            errorMessage += "Le champ " + dtpSalesDate.getName() + " ne peut être ultérieure à la date courante!\n";
        }     

        if(productsListModel.getSize() == 0)
            errorMessage += "Impossible de créer une vente sans articles!\n";
        
        if(!errorMessage.equalsIgnoreCase(""))
        {
            JOptionPane.showMessageDialog(this, errorMessage, "Erreur!", JOptionPane.ERROR_MESSAGE);
        }
        
        return errorMessage.equalsIgnoreCase("");
    }
    
    private void launchSearch(String criteria) 
    {
        salesListModel.clear();
        ArrayList<Vente> salesToShow;
        
        if(!criteria.isEmpty())
            salesToShow = findVente(criteria);
        else
        {
            CatalogueVente catalogue = CatalogueVente.getCatalogueVente();
            salesToShow = catalogue.getVentes();
        }
        
        for(Vente v : salesToShow)
                    salesListModel.addElement(v);
    }

    private ArrayList<Vente> findVente(String criteria) 
    {
        ArrayList<Vente> resultList = new ArrayList<>();
        
        CatalogueVente catalogue = CatalogueVente.getCatalogueVente();
        for(Vente v: catalogue.getVentes())
        {
            if(v.matches(criteria))
                resultList.add(v);
        }
        
        return resultList;
    }
    
    private void saleSelected(Vente sale, boolean isNew)
    {
        if(verifySaveStatus())
        {      
            removeDataChangeListeners();

            isNewSale = isNew;
            currentSale = sale;

            if(currentSale == null)
            {
                salesJList.clearSelection();

                clearFields();
                setFieldsEnabled(false);
                setButtonsEnabled(true , false, false, false);
            }
            else
            {
                clearFields();
                setFieldsValue(currentSale);

                setDataChangeListeners();

                setFieldsEnabled(true);
                setButtonsEnabled(true , true, false, true);
            }
        }
    }

    private void setFieldsValue(Vente selectedSale) 
    {
        lblSubTotal.setText(""+selectedSale.getSousTotal());
        lblTaxes.setText(""+selectedSale.getTaxes());
        lblTotal.setText(""+selectedSale.getTotal());
        dtpSalesDate.setDate(selectedSale.getDate());
        
        clientJComboBox.setSelectedItem(selectedSale.getClient());
        salesmanJComboBox.setSelectedItem(selectedSale.getVendeur());
        //productsListModel
        productsListModel.clear();
        //paymentListModel.clear();
        if(!selectedSale.getListeArticles().isEmpty())
        {
            btnRemoveProduct.setEnabled(true);
        
            for(Article a : selectedSale.getListeArticles())
                productsListModel.addElement(a);
        }
        
        /*for(Paiement p : selectedSale.getListePaiements())
            paymentListModel.addElement(p);*/     
    }
    
    private void setDataChangeListeners()
    {
        dtpSalesDate.addActionListener(dateActionListener);
        
        clientJComboBox.addItemListener(clientSelectionChange);
        salesmanJComboBox.addItemListener(salesmanSelectionChange);
    }
    
    private void removeDataChangeListeners()
    {
        dtpSalesDate.removeActionListener(dateActionListener);
        
        clientJComboBox.removeItemListener(clientSelectionChange);
        salesmanJComboBox.removeItemListener(salesmanSelectionChange);
    }
    
    private class ClientChangeListener implements ItemListener
    {
        @Override
        public void itemStateChanged(ItemEvent evt) 
        {
            if (evt.getStateChange() == ItemEvent.SELECTED && currentSale != null) 
            {
                Client item = (Client)evt.getItem();
                
                setMustSave((item != currentSale.getClient()));
            }
        }
    }
    
    private class SalesmanChangeListener implements ItemListener
    {
        @Override
        public void itemStateChanged(ItemEvent evt) 
        {
            if (evt.getStateChange() == ItemEvent.SELECTED && currentSale != null) 
            {
                Usager item = (Usager)evt.getItem();
                
                setMustSave((item != currentSale.getVendeur()));
            }
        }
    }
    
    private final ListSelectionListener listSelectItemListener = new ListSelectionListener() 
    {
        @Override
        public void valueChanged(ListSelectionEvent evt) 
        {
            int selectedIndex = salesJList.getSelectedIndex();

            if(selectedIndex != -1)
                saleSelected((Vente)(salesListModel.get(selectedIndex)), false);
        }
    };
    
    private final ActionListener dateActionListener = new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent evt)
        {
            updateSaveStatus();
        }
        
        private void updateSaveStatus() 
        {
            setMustSave(true);
        }
    };
    
    private final DocumentListener dateDocumentListener = new DocumentListener()
    {
        @Override
        public void insertUpdate(DocumentEvent e) 
        {
            updateSaveStatus();
        }

        @Override
        public void removeUpdate(DocumentEvent e) 
        {
            updateSaveStatus();
        }

        @Override
        public void changedUpdate(DocumentEvent e) 
        {
        }
        
        private void updateSaveStatus() 
        {
            setMustSave(true);
        }
    };
    
    private final DocumentListener searchDocumentListener = new DocumentListener()
    {
        @Override
        public void insertUpdate(DocumentEvent e) 
        {
            launchSearch(salesSearchJText.getText());
        }

        @Override
        public void removeUpdate(DocumentEvent e) 
        {
            launchSearch(salesSearchJText.getText());
        }

        @Override
        public void changedUpdate(DocumentEvent e) 
        {
            launchSearch(salesSearchJText.getText());
        }
    };
    
    private void cancelJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelJButtonActionPerformed

        saleSelected(null, false);
    }//GEN-LAST:event_cancelJButtonActionPerformed

    private void btnAddProductActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddProductActionPerformed
        addProduct();
    }//GEN-LAST:event_btnAddProductActionPerformed

    private void btnRemoveProductActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveProductActionPerformed
        removeProduct();
    }//GEN-LAST:event_btnRemoveProductActionPerformed

    private void btnRemovePaymentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemovePaymentActionPerformed
        //removePayment();
    }//GEN-LAST:event_btnRemovePaymentActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox articleJComboBox;
    private javax.swing.JButton btnAddPayment;
    private javax.swing.JButton btnAddProduct;
    private javax.swing.JButton btnPrintInvoice;
    private javax.swing.JButton btnRemovePayment;
    private javax.swing.JButton btnRemoveProduct;
    private javax.swing.JButton cancelJButton;
    private javax.swing.JComboBox clientJComboBox;
    private javax.swing.JButton deleteSaleJButton;
    private org.jdesktop.swingx.JXDatePicker dtpSalesDate;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JLabel lblSubTotal;
    private javax.swing.JLabel lblTaxes;
    private javax.swing.JLabel lblTotal;
    private javax.swing.JButton newSaleJButton;
    private javax.swing.JList paymentJList;
    private javax.swing.JList productsJList;
    private javax.swing.JPanel saleDetailsJPanel;
    private javax.swing.JList salesJList;
    private javax.swing.JTextField salesSearchJText;
    private javax.swing.JComboBox salesmanJComboBox;
    private javax.swing.JButton saveSaleJButton;
    // End of variables declaration//GEN-END:variables
}
